package com.bdy.lm.isu.service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.bdy.lm.browser.dao.FareDao;
import com.bdy.lm.browser.dao.TaxiDao;
import com.bdy.lm.browser.domain.CarMeasure;
import com.bdy.lm.browser.domain.LocationTracks;
import com.bdy.lm.browser.domain.ParameterQuery;
import com.bdy.lm.browser.domain.Fare;
import com.bdy.lm.isu.dao.ProcessISURequestDao;
import com.bdy.lm.isu.domain.ISUMessage;
import com.bdy.lm.utils.Utils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class ProcessISURequestService {

	private ProcessISURequestDao processISURequestDao = new ProcessISURequestDao();
	private ISUMessage isuMessageQuery = new ISUMessage();
	//private Gson gson = new Gson();
	private Gson gson = new GsonBuilder().create();
	
	public String chooseMethod(byte[] res) {
		//System.out.println("msg:"+new String(res).toString());
		ISUMessage i = gson.fromJson(new String(res).toString(), ISUMessage.class);
//		System.out.println("msg:"+i.toString());
//		String ISUFlag = Integer.toString(i.getISUFlag_1())
//				+ Integer.toString(i.getISUFlag_company_2())
//				+ Integer.toString(i.getISUFlag_device_3())
//				+ Integer.toString(i.getISUFlag_serialNum_4());
		String ISUFlag = i.getISUFlag();
		int msgID = i.getMessageID();
//		System.out.println("msgID:"+i.toString());
//		System.out.println("MsgId:" + i.getMessageID());
		if(msgID == MsgID.ISULogin) {//请求登录信息
			return login(i,ISUFlag);
		} else if(msgID == MsgID.ISUExit) {//处理签退信息
			return signOut(i, ISUFlag);
		} else if(msgID == MsgID.ISUQueryCommand) {//处理ISU查询指令相关信息
			return commandQuery(i, ISUFlag);
		} else if(msgID == MsgID.ISUExecuteCommandSuccess) {//ISU指令执行成功
			return changeExecute(i, ISUFlag);
		} else if(msgID == MsgID.ISUExecuteCommandFail) {//ISU指令执行失败
			return null;//什么都不做
		} else if(msgID == MsgID.ISUHeartBit) {//处理ISU心跳汇报相关信息
			return heartBit(i, ISUFlag);
		} else if(msgID == MsgID.ISUTransaction) {//处理ISU汇报的交易信息
			return transaction(i, ISUFlag);
		} else if(msgID == MsgID.ISULocation) {//处理定位数据
			return addLocation(i, ISUFlag);
		} else if(msgID == MsgID.ISUQueryFare) {//处理运价查询
			return queryFare(i);
		} else if(msgID == MsgID.ISUQueryVerifyRoute) {//处理请求校准路线
			return getVerifyAdjustRoute(i);
		} else if(msgID == MsgID.ISUVerifyResult) {//处理终端实测上传数据
			return processISUMeasure(i, ISUFlag);
		} else if(msgID == MsgID.queryISUParameter) {//处理终端上传参数
			return processISUParameter(i, ISUFlag);
		} else if(msgID == MsgID.queryTaxiInfo) {//处理终端查询车辆信息
			//System.out.println(new TaxiDao().queryTaxi("ISUFlag", "1616010526880").get(0));
			return gson.toJson(new TaxiDao().queryTaxi("ISUFlag", ISUFlag).get(0));
		} else {
			return null;
		}
	}  

	private String processISUParameter(ISUMessage i, String iSUFlag) {
		ParameterQuery parameterQuery = new ParameterQuery();
		//System.out.println("查询参数1：" + i.getParameter());
		//System.out.println("查询参数2：" + new TaxiDao().queryTaxi("ISUFlag", iSUFlag).get(0).getLicense());
		parameterQuery.setISUFlag(iSUFlag);
		parameterQuery.setLicense(new TaxiDao().queryTaxi("ISUFlag", iSUFlag).get(0).getLicense());
		parameterQuery.setParameter(i.getParameter());
		parameterQuery.setTaximeterTime(i.getTaximeterTime());
		parameterQuery.setQueryTime(i.getQueryTime());
		//System.out.println("查询参数3：" + parameterQuery);
		if (!processISURequestDao.getParameterRepeat(parameterQuery.getQueryTime())) {
			if (processISURequestDao.addISUParameter(parameterQuery)) {
				return "{\"action\":\"115\",\"flag\":\"success\"}";
			} else {
				return "{\"action\":\"115\",\"flag\":\"failure\"}";
			}
		} else {
			return "{\"action\":\"115\",\"flag\":\"success\"}";
		}
	}

	//处理ISU登录相关信息
	private String login(ISUMessage isuMessage, String ISUFlag) {
		try {//防止重复登录
			List<Long> timeStampList = processISURequestDao.queryLoginOutTime(isuMessage.getICID(), isuMessage.getState());
			//查询到客户端连续登陆
			if (timeStampList.size() > 0) {
				long loginDif = Long.parseLong(isuMessage.getLoginOutTime()) - Collections.max(timeStampList);
				//long currentDif = Long.parseLong(isuMessage.getLoginOutTime()) - System.currentTimeMillis();
//				System.out.println("登陆时间：" + Long.parseLong(isuMessage.getLoginOutTime()));
//				System.out.println("最大时间：" + Collections.max(timeStampList));
//				System.out.println("时间差:"+loginDif);
				//如果服务器时间与客户端时间差超过十分钟则提示客户端重新对时，（暂时保留）
				//if (Math.abs(currentDif) < 600000) {	
				//} else {
					//return null;
				//}
				//若客户端第二次与第一次登陆的时间相差5分钟则不写入数据库
				if (loginDif < 300000) {
					return getDriverInfo(isuMessage, ISUFlag, false);
				} else {
					return getDriverInfo(isuMessage, ISUFlag, true);
				}
			} else {
				return getDriverInfo(isuMessage, ISUFlag, true);
			}
		} catch (SQLException e) {
			return "{\"action\":\"101\",\"flag\":\"failure\"}";
		}
	}
	/**
	 * 登录时获取司机信息
	 * @param isuMessage 终端上传数据包
	 * @param ISUFlag 终端序列号
	 * @param isWrite 若为true则将登陆信息写入数据库，false则不写
	 * @return json格式的司机信息
	 */
	private String getDriverInfo(ISUMessage isuMessage, String ISUFlag, boolean isWrite) throws SQLException {
		List<String> isuLoginMsgQueryList = processISURequestDao.queryLoginMessage(isuMessage, ISUFlag);
		isuMessageQuery = isuMessage;
		//System.out.println("查询结果：" + isuLoginMessageQueryList.toString());
		if (isuLoginMsgQueryList.size() > 0) {
			isuMessageQuery.setDriverName(isuLoginMsgQueryList.get(0));// 0 driverName
			isuMessageQuery.setLicense(isuLoginMsgQueryList.get(1));// 1 license
			isuMessageQuery.setDriverCompany(isuLoginMsgQueryList.get(2));// 2 companyName
			isuMessageQuery.setAreaId(isuLoginMsgQueryList.get(3));//3 areaId
			if (isWrite) {
				processISURequestDao.addISULoginOutMessage(isuMessageQuery, ISUFlag);
			}
			return gson.toJson(isuMessageQuery);
		} else {
			isuMessageQuery.setICID("");
			return gson.toJson(isuMessageQuery);
		}
		
	}
	//处理ISU签退相关信息
	private String signOut(ISUMessage isuMessage, String ISUFlag) {

		try {
			List<Long> timeStampList = processISURequestDao.queryLoginOutTime(isuMessage.getICID(), isuMessage.getState());
			if (timeStampList.size() > 0) {
				//System.out.println("size" + timeStampList.size());
				if (Long.parseLong(isuMessage.getLoginOutTime()) - Collections.max(timeStampList) > 5000) {
					processISURequestDao.addISULoginOutMessage(isuMessage, ISUFlag);
				}
			} else {
				processISURequestDao.addISULoginOutMessage(isuMessage, ISUFlag);
			}
			return gson.toJson(isuMessageQuery);
		} catch (SQLException e) {
			return "{\"action\":\"102\",\"flag\":\"failure\"}";
		}
	}
	
	//处理ISU查询指令相关信息
	private String commandQuery(ISUMessage isuMessage, String ISUFlag) {
		try {
			String s = gson.toJson(processISURequestDao.queryCommand(isuMessage, ISUFlag));
			//System.out.println("s" + s);
			return s;
		} catch (SQLException e) {
			return "{\"action\":\"103\",\"flag\":\"failure\"}";
		}
	}

	//处理ISU指令执行情况相关信息
	private String changeExecute(ISUMessage isuMessage, String ISUFlag) {		
		try {
			System.out.println("changeExecute:" + isuMessage);
			if (processISURequestDao.changeExecute(isuMessage, ISUFlag)) {
				return "{\"action\":\"104\",\"flag\":\"success\"}";
			} else {
				return "{\"action\":\"104\",\"flag\":\"failure\"}";
			}
		} catch (SQLException e) {
			return "{\"action\":\"104\",\"flag\":\"failure\"}";
		}
	}
	
	//处理ISU心跳汇报相关信息
	private String heartBit(ISUMessage isuMessage, String ISUFlag) {
		try {
			if (processISURequestDao.addHeartBit(isuMessage, ISUFlag)) {
				return "{\"action\":\"106\",\"flag\":\"success\"}";
			} else {
				return "{\"action\":\"106\",\"flag\":\"failure\"}";
			}
		} catch (SQLException e) {
			return "{\"action\":\"106\",\"flag\":\"failure\"}";
		}
	}
	/**
	 * 处理上传的交易信息
	 * @param isuMessage
	 * @param ISUFlag
	 * @return
	 */
	private String transaction(ISUMessage isuMessage, String ISUFlag) {
		ISUMessage i = isuMessage;
		String locationTracks = null;
		//System.out.println(i.getGetOnTime());
		String distance = i.getDistance();
		try {
			//如果没有相同的信息则写入
			if(!processISURequestDao.queryTransaction(ISUFlag, i.getGetOnTime())) {
				//System.out.println("queryTransaction");
				if(isuMessage.getJourney().equals("single")) {
					i.setJourney("单程");
				} else {
					i.setJourney("往返");
				}
				String evaluate = isuMessage.getEvaluate();
				if (evaluate.equals("satisfaction")) {
					i.setEvaluate("非常满意");
				} else if (evaluate.equals("ordinary")) {
					i.setEvaluate("满意");
				} else if (evaluate.equals("dissatisfaction")) {
					i.setEvaluate("不满意");
				} else if (evaluate.equals("null")) {
					i.setEvaluate("未评价");
				}
				String m = isuMessage.getTransitionType();
				if (m.equals("cash")) {
					i.setTransitionType("现金");
				} else if (m.equals("M1")) {
					i.setTransitionType("M1卡");
				} else if (m.equals("cpu")) {
					i.setTransitionType("CPU卡");
				} else {
					i.setTransitionType("其他方式");
				}
				boolean result;
				if((i.getLocationTracks() != null) && (i.getLocationTracks().size() != 0) && (i.getLocationTracks().get(0) != null)) {
					locationTracks = gson.toJson(i.getLocationTracks());
					result = processISURequestDao.addTransaction(i, ISUFlag, locationTracks, isCheat(i.getLocationTracks(), distance));
				} else {
					result = processISURequestDao.addTransaction(i, ISUFlag, locationTracks, "无记录");
				}
				if(result) {
					return "{\"action\":\"110\",\"flag\":\"success\"}";
				} else {
					return "{\"action\":\"110\",\"flag\":\"failure\"}";
				}
			} else {
				return "{\"action\":\"110\",\"flag\":\"success\"}";
			}
		} catch (SQLException e) {
			return "{\"action\":\"110\",\"flag\":\"failure\"}";
		} catch (IOException e1) {
			return "{\"action\":\"110\",\"flag\":\"failure\"}";
		}
	}
	
	/**
	 * 根据经纬点计算距离与计价器比较是否作弊
	 * @param locationTracks 经纬点集合
	 * @param distance 计价器测量距离，单位：千米
	 * @return 是或者否
	 */
	private String isCheat(List<LocationTracks> locationTracks, String distance) {
		double claculateDistance = 0.0000000001;
		double taximeterCount = Double.valueOf(distance);
		LocationTracks begin = locationTracks.get(0);
		for(LocationTracks lTracks : locationTracks) {
			claculateDistance += Utils.getDistance(begin.getLatitude(), begin.getLongitude(), lTracks.getLatitude(), lTracks.getLongitude());
			begin = lTracks;
		}
		//System.out.println("计价器" + taximeterCount + "GPS" + claculateDistance + " 误差" + (taximeterCount - claculateDistance) / claculateDistance);
		return Utils.doubleFour((taximeterCount - claculateDistance) / claculateDistance * 100) + "% " + Utils.doubleFour(claculateDistance);
	}
	
	private String addLocation(ISUMessage isuMessage, String isu) {
		if(processISURequestDao.addLocation(isuMessage, isu)) {
			return "{\"action\":\"111\",\"flag\":\"success\"}";
		} else {
			return "{\"action\":\"111\",\"flag\":\"failure\"}";
		}
	}
	
	private String queryFare(ISUMessage isuMessage) {
		List<Fare> fares = new FareDao().queryFare("areaId", isuMessage.getAreaId());
		isuMessage.setFare(fares.get(0));
		return gson.toJson(isuMessage);
	}
	
	private String getVerifyAdjustRoute(ISUMessage isuMessage) {
		//System.out.println("StandardRouteNum" + isuMessage.getStandardRouteNum());
		isuMessage.setStandardRoutes(processISURequestDao.queryStandardRoute());
		return gson.toJson(isuMessage);
	}
	
	private String processISUMeasure(ISUMessage i, String isuFlag) {
		CarMeasure carMeasure = i.getCarMeasure();
		//System.out.println("CarMeasure:" + i.getLocationTracks().toString());
		//System.out.println("进来:" + i.getVerifyTime());
		String license = processISURequestDao.queryLicense(isuFlag);
		String verifyTime = Long.toString(Long.parseLong(i.getVerifyTime()) / 1000 * 1000);
//		if (carMeasure.getIsRegular().equals("yes")) {
//			carMeasure.setIsRegular("合格");
//		} else {
//			carMeasure.setIsRegular("不合格");
//		}
		try {
			//如果没有相同的信息则写入
			if (processISURequestDao.queryISUMeasureByVerifyTime(verifyTime)) {
				//System.out.println("有相同：" + i.getVerifyTime());
				return "{\"action\":\"114\",\"flag\":\"success\"}";
			} else {
				if(processISURequestDao.addISUMeasure(carMeasure, isuFlag, license, gson.toJson(i.getLocationTracks()), verifyTime)) {
					//System.out.println("不同:" + i.getVerifyTime());
					return "{\"action\":\"114\",\"flag\":\"success\"}";
				} else {
					return "{\"action\":\"114\",\"flag\":\"failure\"}";
				}
			}
		} catch (SQLException | IOException e) {
			e.printStackTrace();
			return "{\"action\":\"114\",\"flag\":\"failure\"}";
		}
	}
}
